//
//  HYCommonSetViewController.m
//  HYChatProject
//  修改属性
//  Created by Jagtu on 2018/3/3.
//  Copyright © 2018年 erpapa. All rights reserved.
//

#import "HYCommonSetViewController.h"
#import "HYUtils.h"

@interface HYCommonSetViewController () <UITextViewDelegate>

@property(nonatomic,strong)NSString * label;
@property(nonatomic,assign)NSInteger maxNumWords;

@end

@implementation HYCommonSetViewController

-(instancetype)initWithLabel:(NSString *)label finishBlock:(HYSetFinishBlock)block
{
    if (self = [super init]) {
        self.label = label;
        self.finishBlock = block;
        self.hidesBottomBarWhenPushed = YES;
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initData
{
    //昵称、群名片（群聊名称）、群公告（群聊公告）、个性签名
    self.title = [NSString stringWithFormat:@"修改%@",self.label];
    if ([self.label rangeOfString:@"群名称"].location != NSNotFound) {
        self.attrNameLabel.text = @"群聊名称";
        self.maxNumWords = 15;
        
    }else if ([self.label rangeOfString:@"群公告"].location != NSNotFound) {
        self.attrNameLabel.text = @"群聊公告";
        self.maxNumWords = 150;
        
    }else if ([self.label rangeOfString:@"个性签名"].location != NSNotFound) {
        self.attrNameLabel.text = @"个性签名";
        self.maxNumWords = 100;
        
    }else{
        self.attrNameLabel.text = self.label;
        self.maxNumWords = 15;
    }
}

-(void)createView
{
    [self.view addSubview:self.attrNameLabel];
    [self.view addSubview:self.valueTextBgView];
    [self.view addSubview:self.valueTextView];
    [self.view addSubview:self.pnumsLabel];
    [self.view addSubview:self.submitBtn];
}

-(void)layoutSubviews
{
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    
    self.attrNameLabel.frame = CGRectMake(20, 90, screenWidth-40, 25);
    
    self.valueTextBgView.frame = CGRectMake(0, self.attrNameLabel.frame.origin.y+self.attrNameLabel.frame.size.height+5, screenWidth, 5+MAX(self.maxNumWords, 35)+5);
    self.valueTextView.frame = CGRectMake(20, self.valueTextBgView.frame.origin.y+5, screenWidth-40, self.valueTextBgView.frame.size.height-10);
   
    self.pnumsLabel.frame = CGRectMake(20, self.valueTextView.frame.origin.y+self.valueTextView.frame.size.height+5, screenWidth-40, 15);
    
    self.submitBtn.frame = CGRectMake(20, self.valueTextView.frame.origin.y+self.valueTextView.frame.size.height + 35, screenWidth-40, 39);
}

#pragma mark - action
-(void)submitAction
{
    NSString *inputText = [self.valueTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    
    if (inputText.length <= 0) {
        [HYUtils alertWithErrorMsg:@"请输入要设置的内容！"];
        return;
    }else if([self.label rangeOfString:@"邮箱"].location !=NSNotFound){
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})" options:kNilOptions error:NULL];
        NSArray<NSTextCheckingResult *> *results = [regex matchesInString:inputText options:kNilOptions range:NSMakeRange(0, inputText.length)];
        if (!results.count) {
            [HYUtils alertWithErrorMsg:@"错误的邮箱格式！"];
            return;
        }
    }
    if (self.finishBlock) {
        self.finishBlock(self.valueTextView.text);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - lazd

-(UILabel *)attrNameLabel
{
    if (!_attrNameLabel) {
        _attrNameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _attrNameLabel.textColor = COLOR(158,158,158,1);
        _attrNameLabel.font = [UIFont systemFontOfSize:15];
    }
    return _attrNameLabel;
}

-(UIView *)valueTextBgView
{
    if (!_valueTextBgView) {
        _valueTextBgView = [[UIView alloc] initWithFrame:CGRectZero];
        _valueTextBgView.backgroundColor = [UIColor whiteColor];
    }
    return _valueTextBgView;
}

-(UITextView *)valueTextView
{
    if (!_valueTextView) {
        _valueTextView = [[UITextView alloc] initWithFrame:CGRectZero];
        _valueTextView.backgroundColor = [UIColor clearColor];
        _valueTextView.delegate = self;
        _valueTextView.font = [UIFont boldSystemFontOfSize:17];
        
    }
    return _valueTextView;
}


-(UILabel *)pnumsLabel
{
    if (!_pnumsLabel) {
        _pnumsLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _pnumsLabel.textColor = COLOR(189,189,189,1);
        _pnumsLabel.font = [UIFont systemFontOfSize:14];
        _pnumsLabel.textAlignment = NSTextAlignmentRight;
    }
    return _pnumsLabel;
}

-(UIButton *)submitBtn
{
    if (!_submitBtn) {
        _submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_submitBtn setTitle:@"保存" forState:UIControlStateNormal];
        [_submitBtn setBackgroundColor:APP_MAIN_COLOR];
        [_submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_submitBtn.layer setCornerRadius:9.0];
        
        [_submitBtn addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitBtn;
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    NSInteger caninputlen = self.maxNumWords - comcatstr.length;
    
    if (caninputlen >= 0)
    {
        if ([text isEqualToString:@"\n"] && self.maxNumWords <= 31) {
            return NO;
        }
        return YES;
    }
    else
    {
        NSInteger len = text.length + caninputlen;
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0)
        {
            NSString *s = [text substringWithRange:rg];
            
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
        }
        return NO;
    }
    
}

- (void)textViewDidChange:(UITextView *)textView
{
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    
    if (existTextNum > self.maxNumWords)
    {
        //截取到最大位置的字符
        NSString *s = [nsTextContent substringToIndex:self.maxNumWords];
        
        [textView setText:s];
    }
    
    //不让显示负数
    self.pnumsLabel.text = [NSString stringWithFormat:@"%ld/%ld",MAX(0,self.maxNumWords - existTextNum),self.maxNumWords];
}

@end
